package com.wonders.healthcitydoctor.ui.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.wonders.healthcitydoctor.R;
import com.wonders.healthcitydoctor.util.LogUtil;

import java.lang.reflect.Method;

import me.yokeyword.fragmentation.SwipeBackLayout;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;


/**
 */
public abstract class BaseWebviewBackFragment extends SwipeBackFragment implements View.OnClickListener{
    protected String TAG=this.getClass().getSimpleName();
    String className = "com.wonders.healthcity.ui.base.BaseWebviewBackFragment";
    protected View mContentView;
    protected Activity mActivity;

    protected boolean mIsLoadedData = false;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        TAG = this.getClass().getSimpleName();
        mActivity = getActivity();
        LogUtil.i(TAG + "------" + "onAttach");

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isResumed()) {
            handleOnVisibilityChangedToUser(isVisibleToUser);
        }
        LogUtil.i(TAG + "------" + "setUserVisibleHint");
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSwipeBackLayout().setEdgeOrientation(SwipeBackLayout.EDGE_LEFT); // EDGE_LEFT(默认),EDGE_ALL
//        Icepick.restoreInstanceState(this, savedInstanceState);
//        initSwipeBackFinish();
//        EventBus.getDefault().register(this);
//        getSwipeBackLayout().setEdgeOrientation(SwipeBackLayout.EDGE_ALL);
        LogUtil.i(TAG + "------" + "onCreate");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 避免多次从xml中加载布局文件
        LogUtil.i(TAG + "------" + "onCreateView");
        return super.onCreateView(inflater, container, savedInstanceState);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setParallaxOffset(0.5f);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LogUtil.i(TAG + "------" + "onCreateView");
    }

    @Override
    public void onStart() {
        super.onStart();
        LogUtil.i(TAG + "------" + "onStart");
    }
    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            handleOnVisibilityChangedToUser(true);
        }
        LogUtil.i(TAG + "------" + "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getUserVisibleHint()) {
            handleOnVisibilityChangedToUser(false);
        }
        LogUtil.i(TAG + "------" + "onPause");
    }
    @Override
    public void onStop() {
        super.onStop();
        LogUtil.i(TAG + "------" + "onStop");
    }
    @Override
    public void onDetach() {
        super.onDetach();
        LogUtil.i(TAG + "------" + "onDetach");
    }
    public void setTitle(View view, String title){
        ImageView img_back=(ImageView)view.findViewById(R.id.image_back);
        TextView txt_title=(TextView)view.findViewById(R.id.tv_title);
        txt_title.setText(title);
            img_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    _mActivity.onBackPressed();
                pop();
                    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    }
                }
            });
    }
    public void setTitle(View view, String title, String rightText){
        ImageView img_back=(ImageView)view.findViewById(R.id.image_back);
        TextView txt_title=(TextView)view.findViewById(R.id.tv_title);
        TextView right_text=(TextView)view.findViewById(R.id.right_text);
        txt_title.setText(title);
        if (rightText!=null||rightText.equals("")) {
            right_text.setText(rightText);
            right_text.setOnClickListener(this);
        }
            img_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    _mActivity.onBackPressed();
                pop();
                    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    }
                }
            });

    }

    public void setEditTitle(View view, String hint, int leftSrc, int rightSrc){
        ImageView img_left=(ImageView)view.findViewById(R.id.image_left);
        ImageView img_right=(ImageView)view.findViewById(R.id.image_right);
        TextView text_hint=(TextView) view.findViewById(R.id.text_hint);
        final EditText et_title=(EditText) view.findViewById(R.id.et_title);
        final LinearLayout mLayoutDefaultText = (LinearLayout) view.findViewById(R.id.layout_default);
        text_hint.setText(hint);
        if (leftSrc!=0) {
            img_left.setImageResource(leftSrc);
        }
        if (rightSrc!=0) {
            img_right.setImageResource(rightSrc);
        }
        img_left.setOnClickListener(this);
        img_right.setOnClickListener(this);
        et_title.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== EditorInfo.IME_ACTION_DONE){
                    setOnEditClickListener();
                }
                return false;
            }
        });

        // editText 离开监听
        et_title.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // hasFocus 为false时表示点击了别的控件，离开当前editText控件
                if (!hasFocus) {
                    if ("".equals(et_title.getText().toString())) {
                        mLayoutDefaultText.setVisibility(View.VISIBLE);
                    }
                }
                else {
                    mLayoutDefaultText.setVisibility(View.GONE);
                }
            }
        });
    }

    private void initTitleWebview(View view , String title, int leftSrc, final String leftEvent, String rightText, int imgSrc, final String rightEvent){
        ImageView image_left=(ImageView)view.findViewById(R.id.image_left);
        TextView txt_title=(TextView)view.findViewById(R.id.tv_title);
        ImageView image_right=(ImageView)view.findViewById(R.id.image_right);
        TextView right_text=(TextView)view.findViewById(R.id.right_text);
        txt_title.setText(title);
        image_left.setOnClickListener(this);
        if (rightText!=null||rightText.equals("")) {
            right_text.setText(rightText);
            right_text.setOnClickListener(this);
            image_right.setVisibility(View.GONE);
        }else {
            image_right.setImageResource(imgSrc);
            image_right.setOnClickListener(this);
            right_text.setVisibility(View.GONE);
        }
        if (leftSrc!=0){
            image_left.setImageResource(leftSrc);

        }

        image_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                    _mActivity.onBackPressed();
//                leftEvent();

                getReflectMethod(v,leftEvent);

            }
        });
        image_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getReflectMethod(v,rightEvent);
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.image_left:
//            setOnLeftClickListener();
//                leftEvent();

            break;
            case R.id.right_text:
                setOnRightClickListener();
                break;
            case R.id.image_right:
                setOnRightClickListener();
                break;
//            case R.id.right_img:
//                setOnRightClickListener();

        }
    }
    public void setOnLeftClickListener(){


    }
    public void setOnRightClickListener(){
    }
    public void setOnEditClickListener(){
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtil.i(TAG + "------" + "onHiddenChanged");
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        LogUtil.i(TAG + "------" + "onSupportVisible");
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        LogUtil.i(TAG + "------" + "onSupportInvisible");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LogUtil.i(TAG + "------" + "onDestroyView");
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.i(TAG + "------" + "onDestroy");
    }

    public void ToastMessageShort(String message){
        Toast.makeText(getActivity().getApplication(),message, Toast.LENGTH_SHORT).show();
    }
    public void ToastMessageLong(String message){
        Toast.makeText(getActivity().getApplication(),message, Toast.LENGTH_LONG).show();
    }
    /**
     * 处理对用户是否可见
     *
     * @param isVisibleToUser
     */
    private void handleOnVisibilityChangedToUser(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            // 对用户可见
            if (!mIsLoadedData) {
                mIsLoadedData = true;
                onLazyLoadOnce();
            }
            onVisibleToUser();
        } else {
            // 对用户不可见
            onInvisibleToUser();
        }
    }

    /**
     * 懒加载一次。如果只想在对用户可见时才加载数据，并且只加载一次数据，在子类中重写该方法
     */
    protected void onLazyLoadOnce() {
    }

    /**
     * 对用户可见时触发该方法。如果只想在对用户可见时才加载数据，在子类中重写该方法
     */
    protected void onVisibleToUser() {
    }

    /**
     * 对用户不可见时触发该方法
     */
    protected void onInvisibleToUser() {
    }


    /**
     * start other BrotherFragment
     */
//    @Subscribe
//    public void startBrother(StartBrotherEvent event) {
//        start(event.targetFragment);
//    }

    public void back(View v){
        pop();
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
    private void getReflectMethod(View v, String leftEvent){
        String methodName =leftEvent;
        try {
            Class clz = Class.forName(className);
            //
            Object obj = clz.newInstance();
            //获取方法
            Method m = obj.getClass().getDeclaredMethod(methodName, View.class);
            //调用方法
            m.invoke(obj, v);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}